<template>
  <div v-if="isShowPage">
    <dan-form ref="mainForm" :width="width" :formSize="formSize" :formData="formData"></dan-form>
    <el-tabs v-model="activeTabName" type="card" @tab-click="tapTabs" v-if="formSubData.length > 0">
        <el-tab-pane :label="group.formTitle" :name="group.formTitle" v-for="group in formSubData" :key="group.formTitle">
          <dan-form ref="subForm" :width="width" :formSize="formSize" :formData="group.formData"></dan-form>
        </el-tab-pane>
    </el-tabs>
    <div slot="footer" class="dialog-footer">
      <el-button @click="resetForm">重 置</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
    <el-dialog title="模板选择" width="450px" :visible.sync="isShowTemp" :close-on-click-modal="false">
      {{tempName}}模板：
      <el-select  v-model="tempValue" placeholder="请选择模板" :filterable="true" clearable>
        <el-option
          v-for="(item,index) in tempData"
          :key="tempOptions.optionsValueField ? item[tempOptions.optionsValueField] : item.value"
          :label="tempOptions.optionsLabelField ? item[tempOptions.optionsLabelField] : item.label"
          :value="index">
        </el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeTemp">取 消</el-button>
        <el-button type="primary" @click="submitTemp">取 用</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
.my-autocomplete li {line-height: normal;padding: 7px;}
.name {text-overflow: ellipsis; overflow: hidden;}
.addr {font-size: 12px;color: #b4b4b4;}
.highlighted .addr {color: #ddd;}
.dialog-form{padding:20px 50px 5px 20px;}
.dialog-form-sub{padding:20px 50px 5px 20px;}
.dialog-footer{display: flex;justify-content: flex-end;}

</style>
<script>
//submit中的cascaderRadio相关部分，父级默认是空和-1的差别
//submit中的新增和修改的restfulApi风格差别
import {isArray,isString} from '@/utils';
import {editData,addData,getEdit,getSelectData } from '@/api/common.js';

import Tinymce from '@/components/Tinymce';
import uploadImageDrag from '@/components/common/uploadImageDrag';
import danForm from '@/components/common/danForm';
export default {
  components:{danForm,Tinymce,uploadImageDrag},
  props:{
    navTree:{
      type:Object,
      default(){
        return {}
      }
    },
    controller:{
      type:String,
      default(){
        return '';
      }
    },
    resource:{
      default(){
        return 'id';
      }
    },
    formSize:{
      type:String,
      default(){
        return '';
      }
    },
    formData:{
      type:Object,
      default(){
        return {};
      }
    },
    formSubData:{
      type:Array,
      default(){
        return [];
      }
    },
    width:{
      type:String,
      default(){
        return '500px';
      }
    },
    formTypeProp:{
      type:String,
      default(){
        return 'add';
      }
    },
    addActionProp:{
      type:String,
      default(){
        return '';
      }
    },
    getEditActionProp:{
      type:String,
      default(){
        return '';
      }
    },
    editActionProp:{
      type:String,
      default(){
        return '';
      }
    }
  },
  data(){
    return {
      id:0, 
      isShowDialog:false,
      form:{},
      formSub:[],
      activeTabName:'',
      addAction:'',
      editAction:'',
      getEditAction:'',
      formType:'',
      requestParams:{},
      query:{},
      isShowPage:false,
      isShowTemp:false,
      tempField:'',
      tempOptions:{},
      tempData:{},
      tempValue:'',
      tempName:''
    }
  },
  created(){
    this.formType = this.formTypeProp;
    this.addAction = this.addActionProp;
    this.editAction = this.editActionProp;
    this.getEditAction = this.getEditActionProp;
    this.initForm();
  },
  mounted(){

  },
  methods:{
    tapTabs(tab, event) {

    },
    resetForm(){
      this.initForm();
    },
    initForm(query){
      let id = 0;
      if (query && query[this.resource]) {
        this.id = id = query[this.resource];
      }
      if (!id && !this.getEditActionProp && (query || this.navTree.controller)) {
        this.isShowPage = false;
        return;
      };
      this.isShowPage = true;
      return new Promise((resolve,reject)=>{
        this.$nextTick(()=>{
          this.$refs.mainForm.initForm();
          if (this.$refs.subForm) this.$refs.subForm.forEach(item=>{
            item.initForm();
          })
          //如果存在富文本，重置富文本显示内容
          let tinymces = window.tinymce ? window.tinymce.get() : [];
          tinymces.forEach(item=>item.setContent(''));
          this.activeTabName = this.formSubData[0] ? this.formSubData[0].formTitle : '';
          //如果传了ID，代表编辑或复制，获取数据，赋值

          let actionUrl,params = {};
          for (let k in this.$route.query) {
            params[k] = this.$route.query[k];
          }
          if (this.$system.requestApiStyle == 'restful'){
            actionUrl = this.getEditAction ? this.getEditAction : this.controller + '';
            if (isArray(this.resource)){
              console.log('还未做多资源格式的处理');
            } else if (isString(this.resource)){
              if (this.resource) actionUrl += '/'+id;
            }
            params.method = 'GET';
          } else {
            actionUrl = this.getEditAction ? this.getEditAction : this.controller + '/getEditData';      
            if (id) params.data = {id};
            params.method = 'POST';
          }
          getEdit(actionUrl,params).then(data=>{
            this.$refs.mainForm.updateForm(data);
            if (this.$refs.subForm) this.$refs.subForm.forEach(item=>{
              item.updateForm(data);
            })
            resolve();
          })

        });
      });
      
    },
    getSelectData(item){
      //获取下拉选择数据的数据源
      if (item.dataController) {
        getSelectData(item.dataController).then(data=>{
          item.options = data;
        });
      }
    },
    closeForm(){
      //关闭表单
      this.isShowDialog = false;
    },
    openForm(){
      //打开表单
      this.initForm();
      
    },
    isOpen(){
      //获取当前表单状态
      return this.isShowDialog;
    },
    submit(){
      let mainForm = this.$refs.mainForm.getFormData();
      //获取表单数据
      let data = {};
      for (let key in mainForm) {
        if (mainForm[key].type == 'cascaderRadio') {
          if (mainForm[key].value)  {
            if ((typeof mainForm[key].value) == 'object'){
              data[key] = mainForm[key].value.length > 0 ? mainForm[key].value[mainForm[key].value.length - 1] : '';
            } else {
              data[key] = mainForm[key].value;
            }
            
          } else {
            data[key] = '';
          }
        } else {
          data[key] = mainForm[key].value == '0' || mainForm[key].value ? mainForm[key].value : '';
        }

      }
      this.formSubData.forEach((group,groupIndex)=>{
        let subForm = this.$refs['subForm'][groupIndex].getFormData();
        for (let key in subForm) {
          if (subForm[key].type == 'cascaderRadio') {
            if (subForm[key].value && (typeof subForm[key].value) == 'object')  {
              data[key] = subForm[key].value.length > 0 ? subForm[key].value[subForm[key].value.length - 1] : '';
            } else {
              data[key] = '';
            }
          } else if (subForm[key].type == 'pics'){
            data[key] = subForm[key].value.length > 0 ? subForm[key].value : '';
          }else {
            data[key] = subForm[key].value == '0' || subForm[key].value ? subForm[key].value : '';
          }
        }
      })
      for (let key in this.requestParams) {
        data[key] = this.requestParams[key];
      }
      if(this.formType == 'edit') {
        data[this.resource] = this.id;
        let actionUrl = this.editAction ? this.editAction : this.controller + '/editData';
        editData(actionUrl,data).then(data=>{
          this.$tool.succToast( '修改成功');
          this.closeForm();
          this.$emit('submitSuccess');
        });
      } else {
        let actionUrl = this.addAction ? this.addAction : this.controller + '/addData';
        addData(actionUrl,data).then(data=>{
          this.$tool.succToast('新增成功');
          this.closeForm();
          this.$emit('submitSuccess');
        });
      }
      
    },
    setAddAction(action){
      this.addAction = action;
    },
    setEditAction(action){
      this.editAction = action;
    },
    setGetEditAction(action){
      this.getEditAction = action;
    },
    setGetDataAction(){

    },
    setFormType(formType) {
      this.formType = formType;
    },
    setParams(params){
      this.requestParams = params;
    },
    tapAdd(){
      this.$refs.addForm.openForm();
    },
    setQuery(query){
      this.query = query;
      this.initForm(query);
    },
    //模板选择部分开始
    closeTemp(){
      this.isShowTemp = false;
    },
    submitTemp(){
      if (this.tempFormType == 'mainForm'){
        this.$refs.mainForm.updateFieldValue(this.tempField,this.tempData[this.tempValue][this.formData[this.tempField].tempOptions.dataField]);
      } else {
        this.$refs.subForm[this.tempFormIndex].updateFieldValue(this.tempField,this.tempData[this.tempValue][this.formSubData[this.tempFormIndex].formData[this.tempField].tempOptions.dataField]);
      }
      this.isShowTemp = false;
    },
    tapTempMain(field){
      this.tempFormType = 'mainForm';
      this.tempFormIndex = '';
      this.showTempPicker(field);
    },
    tapTempSub(subFormIndex,field){
      this.tempFormType = 'subForm';
      this.tempFormIndex = subFormIndex;
      this.showTempPicker(field);
    },
    showTempPicker(field){
      let c = this.tempFormType == 'mainForm' ? this.formData[field].tempOptions.dataController :  this.formSubData[this.tempFormIndex].formData[field].tempOptions.dataController;
      let params = {
        c
      }
      this.$request(params).then(data=>{
        this.tempData = data;
      })
      this.tempField = field;
      this.tempValue = '';
      this.tempName = this.tempFormType == 'mainForm' ? this.formData[field].label :  this.formSubData[this.tempFormIndex].formData[field].label;
      this.isShowTemp = true;
    }
    //模板选择的部分结束
  },
  computed:{
    title(){
      return this.formType == 'edit' ? '编辑内容' : '新增内容';
    }
  }
}


</script>